
package org.sopt.dev.ImgKnight.monitor.nio;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.sopt.dev.ImgKnight.monitor.Monitor;


@ChannelPipelineCoverage("all")
public class NioStringStreamHandler extends SimpleChannelHandler {
	
	private Monitor monitor = null;
	
	public NioStringStreamHandler(Monitor monitor) {
		this.monitor = monitor;
	}
	
	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
		e.getChannel().getPipeline().addFirst("encoder", new StringEncoder());
		e.getChannel().getPipeline().addFirst("decoder", new StringDecoder());
		e.getChannel().getPipeline().addFirst("framer", 
				new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
	}
	
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		monitor.removePeer(e.getChannel());
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		/* TODO */
	}
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		monitor.parseResponse(e.getChannel(), (String)e.getMessage());
	}
	
}


